using System;
using System.Collections.Generic;
using System.Text;
using SqlTools.DataAccessLibrary;
using System.Data;
using SqlTools.SampleDAL.Data;

namespace SqlTools.SampleDAL
{
	public partial class User_Role : BusinessObject, IDbObject<User_RolePrimaryKey>
	{
		protected User_RolePrimaryKey _user_rolePrimaryKey;
		protected User _user;
		protected Role _role;

		public User_Role()
		{
			_user_rolePrimaryKey = new User_RolePrimaryKey();
			_user = null;
			_role = null;
		}

		#region IDbObject<User_RolePrimaryKey> Members

		public User_RolePrimaryKey Key
		{
			get { return _user_rolePrimaryKey; }
		}

		#endregion

		public User User
		{
			get
			{
				if ( _user == null && this.Key.UserID != 0 )
				{
					DbUser dbUser;
					if ( !string.IsNullOrEmpty(_ConnectionStringName) )
						dbUser = new DbUser(_ConnectionStringName);
					else
						dbUser = new DbUser();

					_user = dbUser.SelectByPK(new UserPrimaryKey(this.Key.UserID));
				}

				return _user;
			}
			set
			{
				if ( _user != value )
				{
					_user = value;

					if ( _user != null )
						this.Key.UserID = _user.Key.UserID;
					else
						this.Key.UserID = 0;

					_UpdateState();
				}
			}
		}

		public Role Role
		{
			get
			{
				if ( _role == null && this.Key.RoleID != 0 )
				{
					DbRole dbRole;
					if ( !string.IsNullOrEmpty(_ConnectionStringName) )
						dbRole = new DbRole(_ConnectionStringName);
					else
						dbRole = new DbRole();

					_role = dbRole.SelectByPK(new RolePrimaryKey(this.Key.RoleID));
				}

				return _role;
			}
			set
			{
				if ( _role != value )
				{
					_role = value;

					if ( _role != null )
						this.Key.RoleID = _user.Key.UserID;
					else
						this.Key.RoleID = 0;

					_UpdateState();
				}
			}
		}

		public override void Update()
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public override void Insert()
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public override void Delete()
		{
			throw new Exception("The method or operation is not implemented.");
		}

		protected DbUser_Role CreateDbUser_Role()
		{
			if ( !string.IsNullOrEmpty(_ConnectionStringName) )
				return new DbUser_Role(_ConnectionStringName);
			else
				return new DbUser_Role();
		}

		public static User_Role CreateFromReader(IDataReader reader)
		{
			User_Role urole = new User_Role();

			FillFromReader(urole, reader);

			return urole;
		}

		public static void FillFromReader(User_Role urole, IDataReader reader)
		{
			urole.OnLoading(urole);

			urole.Key.UserID = (int)reader["UserID"];
			urole.Key.RoleID = (int)reader["RoleID"];

			urole._UpdateState(ObjectState.None);

			urole.OnLoaded(urole);
		}
	}
}
